package com.linln.admin.system.controller;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.linln.admin.system.validator.AreaValid;
import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.EntityBeanUtil;
import com.linln.common.utils.HttpServletUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.vo.ResultVo;
import com.linln.component.actionLog.action.SaveAction;
import com.linln.component.actionLog.annotation.ActionLog;
import com.linln.component.actionLog.annotation.EntityParam;
import com.linln.modules.member.domain.MemberAgent;
import com.linln.modules.member.domain.MemberInfo;
import com.linln.modules.member.service.MemberAgentService;
import com.linln.modules.system.domain.Area;
import com.linln.modules.system.service.AreaService;

/**
 * @author 小懒虫
 * @date 2018/8/14
 */
@Controller
@RequestMapping("/system/area")
public class AreaController {

    @Autowired
    private AreaService areaService;
    @Autowired
    private MemberAgentService memberAgentService;
   

    /**
     * 跳转到列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("system:area:index")
    public String index(Model model) {
        String search = HttpServletUtil.getRequest().getQueryString();
        model.addAttribute("search", search);
        return "/system/area/index";
    }

    /**
     * 菜单数据列表
     */
    @GetMapping("/list")
    @RequiresPermissions("system:area:index")
    @ResponseBody
    public ResultVo list(Area area) {
        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching().
                withMatcher("name", match -> match.contains());

        // 获取菜单列表
        Example<Area> example = Example.of(area, matcher);
        Sort sort = new Sort(Sort.Direction.ASC, "sort");
        List<Area> list = areaService.getListByExample(example, sort);

        return ResultVoUtil.success(list);
    }

    /**
     * 获取排序菜单列表
     */
    @GetMapping("/sortList/{pid}/{notId}")
    @RequiresPermissions({"system:area:add", "system:area:edit"})
    @ResponseBody
    public Map<Integer, String> sortList(
            @PathVariable(value = "pid", required = false) Long pid,
            @PathVariable(value = "notId", required = false) Long notId){
        // 本级排序菜单列表
        notId = notId != null ? notId : (long) 0;
        List<Area> levelMenu = areaService.getListByPid(pid, notId);
        Map<Integer, String> sortMap = new TreeMap<>();
        for (int i = 1; i <= levelMenu.size(); i++) {
            sortMap.put(i, levelMenu.get(i - 1).getName());
        }
        return sortMap;
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping({"/add", "/add/{pid}"})
    @RequiresPermissions("system:area:add")
    public String toAdd(@PathVariable(value = "pid", required = false) Area pArea, Model model) {
        model.addAttribute("pArea", pArea);
        return "/system/area/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("system:area:edit")
    public String toEdit(@PathVariable("id") Area area, Model model) {
        Area pMenu = areaService.getById(area.getPid());
        model.addAttribute("area", area);
        model.addAttribute("pArea", pMenu);
        return "/system/area/add";
    }

    /**
     * 保存添加/修改的数据
     * @param valid 验证对象
     * @param menu 实体对象
     */
    @PostMapping("/save")
    @RequiresPermissions({"system:area:add", "system:area:edit"})
    @ResponseBody
    @ActionLog(name = "区域管理", message = "区域：${name}", action = SaveAction.class)
    public ResultVo save(@Validated AreaValid valid, @EntityParam Area area) {
         if (area.getId() == null) {
            // 排序为空时，添加到最后
            if(area.getSort() == null){
                Integer sortMax = areaService.getSortMax(area.getPid());
                area.setSort(sortMax !=null ? sortMax - 1 : 0);
            }
        }

        if(area.getMemberId()!=null && area.getMemberId()>0) {
        	area.setIsagent(1);
        }
        // 添加/更新全部上级序号
        Area pMenu = areaService.getById(area.getPid());
        area.setPids(pMenu.getPids() + ",[" + area.getPid() + "]");
        
        // 复制保留无需修改的数据
        if (area.getId() != null) {
            Area beArea = areaService.getById(area.getId());
            if(beArea.getMemberId()!=null && beArea.getMemberId()>0) {
            	if(!beArea.getMemberId().equals(area.getMemberId())) {
            		//代表原来有代理商 现在进行改变 将原来的代理商替换掉
                    MemberAgent	memberAgent=memberAgentService.getByMemberIdAndArea(area.getMemberId(), area.getCode());
                    if(memberAgent==null) {
                    	memberAgent=new MemberAgent();
                        memberAgent.setAllmoney(0D);
                        memberAgent.setArea(area.getCode());
                        memberAgent.setAreaname(area.getName());
                        memberAgent.setCurmoney(0D);
                        MemberInfo memberInfo=new MemberInfo();
                        memberInfo.setId(area.getMemberId());
                        memberAgent.setStatus(StatusEnum.OK.getCode());
                        memberAgent.setMember(memberInfo);
                        memberAgentService.save(memberAgent);
                    }else {
                    	//memberAgent.setAllmoney(0D);
                        memberAgent.setArea(area.getCode());
                        memberAgent.setAreaname(area.getName());
                        //memberAgent.setCurmoney(0D);
                        MemberInfo memberInfo=new MemberInfo();
                        memberInfo.setId(area.getMemberId());
                        memberAgent.setStatus(StatusEnum.OK.getCode());
                        memberAgent.setMember(memberInfo);
                        memberAgentService.save(memberAgent);
                    }
            	}
            }else {
            	//原来没有的情况下
            	//代表原来有代理商 现在进行改变 将原来的代理商替换掉
                MemberAgent	memberAgent=memberAgentService.getByMemberIdAndArea(area.getMemberId(), area.getCode());
                if(memberAgent==null) {
                	memberAgent=new MemberAgent();
                    memberAgent.setAllmoney(0D);
                    memberAgent.setArea(area.getCode());
                    memberAgent.setAreaname(area.getName());
                    memberAgent.setCurmoney(0D);
                    MemberInfo memberInfo=new MemberInfo();
                    memberInfo.setId(area.getMemberId());
                    memberAgent.setStatus(StatusEnum.OK.getCode());
                    memberAgent.setMember(memberInfo);
                    memberAgentService.save(memberAgent);
                }else {
                	//memberAgent.setAllmoney(0D);
                    memberAgent.setArea(area.getCode());
                    memberAgent.setAreaname(area.getName());
                    //memberAgent.setCurmoney(0D);
                    MemberInfo memberInfo=new MemberInfo();
                    memberInfo.setId(area.getMemberId());
                    memberAgent.setStatus(StatusEnum.OK.getCode());
                    memberAgent.setMember(memberInfo);
                    memberAgentService.save(memberAgent);
                }
            }
            EntityBeanUtil.copyProperties(beArea, area);
            area.setFirstletter(beArea.getFirstletter()); 
        }else {
        	
        	
            MemberAgent	memberAgent=memberAgentService.getByMemberIdAndArea(area.getMemberId(), area.getCode());
            if(memberAgent==null) {
            	memberAgent=new MemberAgent();
                memberAgent.setAllmoney(0D);
                memberAgent.setArea(area.getCode());
                memberAgent.setAreaname(area.getName());
                memberAgent.setCurmoney(0D);
                MemberInfo memberInfo=new MemberInfo();
                memberInfo.setId(area.getMemberId());
                memberAgent.setStatus(StatusEnum.OK.getCode());
                memberAgent.setMember(memberInfo);
                memberAgentService.save(memberAgent);
            }else {
            	//memberAgent.setAllmoney(0D);
                memberAgent.setArea(area.getCode());
                memberAgent.setAreaname(area.getName());
                //memberAgent.setCurmoney(0D);
                MemberInfo memberInfo=new MemberInfo();
                memberInfo.setId(area.getMemberId());
                memberAgent.setStatus(StatusEnum.OK.getCode());
                memberAgent.setMember(memberInfo);
                memberAgentService.save(memberAgent);
            }
        	


        	
        }

        // 排序功能
        Integer sort = area.getSort();
        Long notId = area.getId() != null ? area.getId() : 0;
        List<Area> levelArea = areaService.getListByPid(area.getPid(), notId);
        levelArea.add(sort, area);
        for (int i = 1; i <= levelArea.size(); i++) {
            levelArea.get(i - 1).setSort(i);
        }
        
        // 保存数据
        areaService.save(levelArea);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("system:area:detail")
    public String toDetail(@PathVariable("id") Area area, Model model) {
        model.addAttribute("area", area);
        return "/system/area/detail";
    }


}
